package com.shop.cloud.ueditor.service;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.shop.cloud.config.ConfigUtil;
import com.shop.cloud.ueditor.util.FileNameUtils;
import com.shop.cloud.ueditor.util.upload.FileRepository;
import com.shop.cloud.ueditor.util.upload.UploadUtils;

@Component
public class ImageService {
	

	
	@Autowired
	protected FileRepository fileRepository;
	@Autowired
	private ConfigUtil configUtil;
	/**
	 * 上传文件存储的绝对路径
	 */
	/*@Value("${upload.absolute.file.path}")
	private String uploadFilePath;
	*//**
	 * 访问的base路径
	 *//*
	@Value("${upload.access.file.path}")
	private String baseServerUrl;*/
	
	private String uploadFilePath="D:\\\\chsi\\\\";

	private String baseServerUrl="http://127.0.0.1:8080/chsi/";
	
	public String crawlImg(String imgUrl) {
		CloseableHttpClient client = HttpClientBuilder.create().build();
		String outFileName = "";
		String fileUrl = "";
		try {
			HttpGet httpget = new HttpGet(new URI(imgUrl));
			HttpResponse response = client.execute(httpget);
			InputStream is = null;
			OutputStream os = null;
			HttpEntity entity = null;
			entity = response.getEntity();
			is = entity.getContent();
			String ext = FileNameUtils.getFileSufix(imgUrl);
			outFileName = UploadUtils.generateFilename(uploadFilePath, ext);
			File outFile = new File(configUtil.getUploadAbsoluteFilePath(),outFileName);
			UploadUtils.checkDirAndCreate(outFile.getParentFile());
			os = new FileOutputStream(outFile);
			IOUtils.copy(is, os);
			fileUrl = baseServerUrl + outFileName;
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return fileUrl;
	}
}
